package shop;

import java.util.List;

import javax.persistence.EntityManager;
//import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
//import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class DBProductService implements DBProduct{
	
	//private SessionFactory sessionFactory;
	@PersistenceContext
	private EntityManager em;
	
	//@Autowired
	//public void setSessionFactory(EntityManagerFactory emf){
		//this.emf = emf;
	//}
	
	public boolean createProduct(Product product){
		boolean result = false;
		try{
			//Session s = sessionFactory.getCurrentSession();
			//EntityManager em = emf.createEntityManager();
			//s.save(product);
			em.persist(product);
			result = true;
		}catch(RuntimeException e){
			throw e;
		}
		return result;
	}
	
	public boolean deleteProduct(long ProductID){
		boolean result = false;
		try{
			//Session s = sessionFactory.getCurrentSession();
			//EntityManager em = emf.createEntityManager();
			//s.delete(getProduct(ProductID));
			em.remove(getProduct(ProductID));
			result = true;
		}catch(RuntimeException e){
			throw e;
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Product> listAllProduct(){
		//Session s = sessionFactory.getCurrentSession();
		//EntityManager em = emf.createEntityManager();
		//Query query = s.createQuery("select p from Product p ");
		Query query = em.createQuery("select p from Product p ");
		return query.getResultList();
	}
	
	public boolean checkProduct(long ProductID){
		try{
			Product p = getProduct(ProductID);
			return p != null;
		}catch(RuntimeException e){
			return false;
		}
	}
	
	public Product getProduct(long ProductID){
		//Session s = sessionFactory.getCurrentSession();
		//EntityManager em = emf.createEntityManager();
		Query query = em.createQuery("select p from Product p where p.id=:ID ");
		query.setParameter("ID", ProductID);
		return (Product)query.getSingleResult();
	}
}
